package com.alittle.support.support.widget;

import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.view.View;

/**
 * Created by xe on 15-6-28.
 * 圆形色彩背景
 */
class TintColorDrawable extends GradientDrawable {

    private static void setTintCircleColorList(View view, int color, ColorStateList colorStateList) {
        TintColorDrawable tintColorDrawable = new TintColorDrawable();
        tintColorDrawable.setShape(GradientDrawable.OVAL);

        if (colorStateList == null) {
            tintColorDrawable.setTintCircleColors(null);
            tintColorDrawable.setColor(color);
        } else {
            tintColorDrawable.setTintCircleColors(colorStateList);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            view.setBackground(tintColorDrawable);
        } else {
            view.setBackgroundDrawable(tintColorDrawable);
        }
    }

    public static void setTintCircleColorList(View view, ColorStateList colorStateList) {
        setTintCircleColorList(view, Color.TRANSPARENT, colorStateList);
    }

    public static void setTintCircleColor(View view, int color) {
        setTintCircleColorList(view, color, null);
    }

    private ColorStateList colorStateList;

    public void setTintCircleColors(ColorStateList colorStateList) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setColor(colorStateList);
        } else {
            this.colorStateList = colorStateList;
            if (colorStateList == null) {
                setColor(Color.TRANSPARENT);
            } else {
                setColor(colorStateList.getDefaultColor());
            }
        }
    }

    @Override
    public boolean isStateful() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return super.isStateful();
        } else {
            return colorStateList != null;
        }
    }

    @Override
    protected boolean onStateChange(int[] stateSet) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            return super.onStateChange(stateSet);
        } else {
            if (colorStateList == null) {
                return false;
            }
            setColor(colorStateList.getColorForState(stateSet, Color.TRANSPARENT));
            invalidateSelf();
            return true;
        }
    }
}
